/*
 * @Author: fanjs
 * @Date: 2025-03-04 15:51:29
 * @Description: 上传组件
 */

import React, { useState } from 'react';
import type { UploadProps } from 'antd';
import { Upload } from 'antd';
import { SvgIcon } from '@/components/SvgIcon'
import { localStg } from '@/utils/storage';
import { getServiceBaseURL } from '@/utils/service';
import { addToast, Spinner } from '@heroui/react';

const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL } = getServiceBaseURL(import.meta.env as any, isHttpProxy);

const { Dragger } = Upload;

interface UploadComponentProps {
  data?: {
    task_id: string;
    template_id: string;
    columns: {
      [key: string]: string;
    };
  };
  onSuccess: (list: any[]) => void;
}

const UploadComponent: React.FC<UploadComponentProps> = ({ data, onSuccess }) => {
  const action = `${baseURL}/v1/email-recipient/upload`

  const [isLoading, setIsLoading] = useState<boolean>(false);

  const props: UploadProps = {
    name: 'file',
    multiple: false,
    maxCount: 1,
    action,
    data,
    headers: {
      Authorization: `Bearer ${localStg.get('token')}`,
    },
    onChange(info) {
      const { status } = info.file;
      setIsLoading(true)
      // 上传完成
      if (status === 'done') {
        const { data } = info.file.response;
        if (data) onSuccess(data)
        setIsLoading(false)
      } else if (status === 'error') {
        setIsLoading(false)
        addToast({ title: `${info.file.response.msg}` })
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  return (
    <div className='relative'>
      {isLoading && <div className='wh-full absolute top-0 left-0 flex-center bg-default-50 z-40 rounded-lg'>
        <Spinner classNames={{ label: "text-secondary mt-2" }} label="正在解析，请稍候..." color="secondary" variant="gradient" />
      </div>
      }
      <Dragger {...props}>
        <p className="flex-center mb-2">
          <SvgIcon icon="ri:upload-2-line" className='text-3xl text-secondary' />
        </p>
        <p className="text-secondary my-2 text-[14px]">点击或拖动文件到此处上传</p>
        <p className="text-secondary text-[12px]">
          上传 Excel 文件后会自动开始解析文档数据，请耐心等待
        </p>
      </Dragger>
    </div>
  );
};

export default UploadComponent;
